<template>
  <div v-if="!item.hidden" >
    <template v-if="hasOneShowingChild(item.children,item)">
        <el-menu-item :index="resolvePath(onlyOneChild.url)">
          <i :class="[item.icon]"></i>
          <span>{{ item.title }}</span>
        </el-menu-item>
    </template>

    <el-submenu v-else ref="subMenu" :index="item.id+''"  popper-append-to-body>
      <template slot="title">
        <i :class="[item.icon]"></i>
          <span>{{ item.title }}</span>
      </template>
      <sidebar-item
        v-for="child in item.children"
        :key="child.id"
        :is-nest="true"
        :item="child"
        :base-path="resolvePath(child.url)"
        class="nest-menu"
      />
    </el-submenu>
  </div>
</template>

<script>
import path from 'path'
import { isExternal } from '@/utils/validate'
import Item from './Item'

export default {
  name: 'SidebarItem',
  components: { Item },
  props: {
    // route object
    item: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: ''
    }
  },
  data() {

    // TODO: refactor with render function
    this.onlyOneChild = null
    return {}
  },
  methods: {
    hasOneShowingChild(children =[], parent) {
      if (children==null) {
        children=[];
      }
      const showingChildren = children.filter(item => {
          // Temp set(will be used if only has one showing child)
          this.onlyOneChild = item
          return true
      })


      // Show parent if there are no child router to display
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return true
      }

      return false
    },
    resolvePath(routePath) {
      if (isExternal(routePath)) {
        return routePath
      }
      if (isExternal(this.basePath)) {
        return this.basePath
      }
      return path.resolve(this.basePath, routePath)
    }
  }
}
</script>
